﻿using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
using Unity.Mathematics;

namespace Game.FlowField.Burst
{
    [BurstCompile]
    public struct UnitAddingJob : IJob
    {
        [ReadOnly]
        public int2 MapSize;

        /// <summary>
        /// Input
        /// </summary>
        [ReadOnly]
        public NativeArray<int2> AddingGridIndex2Ds;

        /// <summary>
        /// Input
        /// </summary>
        [ReadOnly]
        public NativeArray<float2> GridPositions;

        /// <summary>
        /// Input
        /// </summary>
        [ReadOnly]
        public NativeArray<bool> GridIsBlocks;

        /// <summary>
        /// Input Output
        /// </summary>
        public NativeArray<int> GridOccupies;

        /// <summary>
        /// Input Output
        /// </summary>
        public NativeArray<FlexibleArray<Unit>> Units;

        [BurstDiscard]
        public void WrapData(MapData mapData, NativeArray<int2> addingGridIndex2Ds, NativeArray<FlexibleArray<Unit>> units)
        {
            this.MapSize = mapData.Size;
            this.AddingGridIndex2Ds = addingGridIndex2Ds;
            this.GridOccupies = mapData.GridOccupies;
            this.Units = units;
            this.GridPositions = mapData.GridPositions;
            this.GridIsBlocks = mapData.GridIsBlocks;
        }

        [BurstCompile]
        public void Execute()
        {
            var units = this.Units[0];

            for (int i = 0; i < this.AddingGridIndex2Ds.Length; i++)
            {
                var addingIndex2D = this.AddingGridIndex2Ds[i];
                if (!MapDataUtil.IsInsideMap(addingIndex2D, this.MapSize))
                    continue;

                var addingIndex = MapDataUtil.ConvertIndex2D2Index(addingIndex2D, this.MapSize);
                var occupy = this.GridOccupies[addingIndex];
                if (occupy == 0 && !this.GridIsBlocks[addingIndex])
                {
                    this.GridOccupies[addingIndex] = occupy + 1;
                    var unit = new Unit();
                    unit.ResetAsNewOne();
                    unit.Setup(addingIndex, this.GridPositions[addingIndex]);
                    units.Add(unit);
                }
            }

            this.Units[0] = units;
        }
    }
}